// pages/task/task.js
const db = wx.cloud.database()
const TASK_RESET_HOUR = 0 // 每日0点刷新

Page({
  data: {
    tasks: [],
    userPoints: 0,
    lastRefreshDate: ''
  },

  onLoad() {
    this.loadUserData()
    this.checkTaskRefresh()
  },

  // 加载用户数据（更新本地缓存）
  async loadUserData() {
    const user = wx.getStorageSync('userInfo')
    if (user) {
      try {
        const { data } = await db.collection('users').doc(user._id).get()
        // 同步最新数据到本地缓存
        const updatedUser = { ...user, ...data }
        wx.setStorageSync('userInfo', updatedUser)
        
        this.setData({
          userPoints: data.points,
          lastRefreshDate: this.formatDate(data.lastTaskRefresh)
        })
      } catch (err) {
        console.error('加载用户数据失败:', err)
      }
    }
  },

  // 检查任务是否需要刷新
  async checkTaskRefresh() {
    const user = wx.getStorageSync('userInfo')
    if (!user) return

    try {
      const { data } = await db.collection('users').doc(user._id).get()
      const lastRefresh = new Date(data.lastTaskRefresh)
      const now = new Date()
      
      // 判断是否需要刷新任务
      if (
        now.getDate() !== lastRefresh.getDate() ||
        now.getMonth() !== lastRefresh.getMonth() ||
        now.getFullYear() !== lastRefresh.getFullYear()
      ) {
        await this.resetDailyTasks(user._id)
      } else {
        this.setData({ tasks: data.dailyTasks })
      }
    } catch (err) {
      console.error('检查任务刷新失败:', err)
    }
  },

  // 重置每日任务
  async resetDailyTasks(userId) {
    const defaultTasks = [
      { id:1,title: '每日签到', description: '登录应用即可完成', points: 10, completed: false },
      { id:2,title: '主页浏览', description: '在主页进行浏览', points: 20, completed: false },
      { id:3,title: '社区互动', description: '参与话题讨论', points: 30, completed: false },
      { id:4,title: '游戏体验', description: '体验拼图游戏', points: 40, completed: false },
      { id:5,title: '知识学习', description: '进行知识学习', points: 50, completed: false }
    ]

    try {
      await db.collection('users').doc(userId).update({
        data: {
          dailyTasks: defaultTasks,
          lastTaskRefresh: db.serverDate()
        }
      })

      // 更新本地缓存
      const user = wx.getStorageSync('userInfo')
      const updatedUser = { 
        ...user, 
        dailyTasks: defaultTasks,
        lastTaskRefresh: new Date() 
      }
      wx.setStorageSync('userInfo', updatedUser)

      this.setData({
        tasks: defaultTasks,
        lastRefreshDate: this.formatDate(new Date())
      })
    } catch (err) {
      console.error('重置任务失败:', err)
    }
  },

  // 完成任务（更新本地和云端）
  async completeTask(e) {
    const index = e.currentTarget.dataset.index
    if(index == 1 ){
      wx.switchTab({ url: '/pages/index/index' });
    }else if(index == 2){
      wx.switchTab({ url: '/pages/Discussions/Discussions' });
    }else if(index == 3){
      wx.navigateTo({ url: '/pages/puzzleGame/puzzleGame' });
    }else if(index == 4){
      wx.switchTab({ url: '/pages/examList/examList' });
    }
    const user = wx.getStorageSync('userInfo')
    if (!user) return

    try {
      // 更新任务状态
      const updatedTasks = this.data.tasks.map((task, i) => 
        i === index ? { ...task, completed: true } : task
      )

      // 计算新积分
      const pointsToAdd = this.data.tasks[index].points
      const newPoints = this.data.userPoints + pointsToAdd

      // 更新云端
      await db.collection('users').doc(user._id).update({
        data: {
          dailyTasks: updatedTasks,
          points: newPoints
        }
      })

      // 更新本地缓存
      const updatedUser = { 
        ...user, 
        points: newPoints,
        dailyTasks: updatedTasks 
      }
      wx.setStorageSync('userInfo', updatedUser)

      // 更新页面数据
      this.setData({
        tasks: updatedTasks,
        userPoints: newPoints
      })

      wx.showToast({
        title: `+${pointsToAdd}积分`,
        icon: 'success'
      })
    } catch (err) {
      console.error('完成任务失败:', err)
      wx.showToast({ title: '操作失败，请重试', icon: 'none' })
    }
  },

  // 日期格式化
  formatDate(date) {
    const d = new Date(date)
    return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
  }
})